//
//  APPLEComposePictureView.swift
//  123
//
//  Created by pangjiaxing on 16/1/11.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit
import SVProgressHUD
protocol APPLEComposePictureCellDelegate : NSObjectProtocol{
    func deleteButtonClick(indexpath:NSIndexPath)
}

class APPLEComposePictureView: UICollectionView {
    
    private let  APPLEComposePictureViewIdentifier:String="APPLEComposePictureViewIdentifier"
    lazy var images : [UIImage] = [UIImage]()
    
    private  override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    var  addImagesClourse:(()->())?
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        registerClass(APPLEComposePictureCell.self, forCellWithReuseIdentifier: APPLEComposePictureViewIdentifier)
        hidden = true
        dataSource = self
        delegate = self
        
        let itemMargin:CGFloat = 5
        let itemH:CGFloat = (mainScreenW-2*APPLEComposeViewControllerMargin-2*itemMargin)/3
        let itemW=itemH
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = CGSize(width: itemW, height: itemH)
//        print(layout.itemSize)
        layout.minimumInteritemSpacing=itemMargin
        layout.minimumLineSpacing=itemMargin
        
        
    }
    
    func addImage(image:UIImage){
        
        if images.count == 9 {
            SVProgressHUD.showErrorWithStatus("图片太多了，小伙子")
            return
        }
        hidden = false
        images.append(image)
        reloadData()
    }
}

extension APPLEComposePictureView:UICollectionViewDataSource,UICollectionViewDelegate,APPLEComposePictureCellDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
//        return images.count
        return (images.count == 0 || images.count == 9) ? images.count : images.count+1
       
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(APPLEComposePictureViewIdentifier, forIndexPath: indexPath) as!APPLEComposePictureCell
        if indexPath.item == images.count{
            cell.image = nil
        }else{
            cell.image = images[indexPath.item]
        }
       cell.indexPath  = indexPath
        cell.delegate = self
        return cell
    }
    func deleteButtonClick(indexpath: NSIndexPath) {
        images.removeAtIndex(indexpath.item)
        reloadData()
        if images.count == 0 {
            hidden = true
        }
    }
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        if indexPath.item == images.count {
            addImagesClourse?()
        }
    }
    
}



private class APPLEComposePictureCell:UICollectionViewCell {
    
    weak var delegate : APPLEComposePictureCellDelegate?
    private lazy var imageView:UIImageView = UIImageView()
    
    private lazy var deleteButton:UIButton = {
        let button:UIButton = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.addTarget(self, action: "didDeleteButton", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    @objc private func didDeleteButton(){
        delegate?.deleteButtonClick(indexPath!)
    }
    
    var indexPath : NSIndexPath?
    var image:UIImage?{
        didSet{
            
            if image == nil{
                
                // 当前显示加号按钮
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                // 隐藏删除按钮
                deleteButton.hidden = true
                
            }else{
            
                imageView.image = image
                imageView.highlightedImage=nil
                deleteButton.hidden = false
                
            }
           
        
        }
    }
    
    private override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
//        imageView.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView)
            make.trailing.equalTo(contentView)
        }
        
    }
}